//
//  AppDelegate.m
//  PBHomeDemo
//
//  Created by Playboy on 2017/11/21.
//  Copyright © 2017年 tmkj. All rights reserved.
//

#import "AppDelegate.h"
#import "TMTabBarViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiManager.h"
#import "WXApi.h"
#import "PBPaySuccessViewController.h"
#import "TMGuideViewController.h"
#import "JPUSHService.h"
#import "JCAlertView.h"
#import "PBLoginViewController.h"
#import "UIApplication+Visible.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

#define kUDFirstLaunchVersionString  @"UDFirstLaunchVersionString"

@interface AppDelegate ()<JPUSHRegisterDelegate>

@property (nonatomic, strong) JCAlertView *alert;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    [self registjPushWith:launchOptions];
    
    // 判断是否是第一次启动
    NSString *first = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    if ([kUserDefaults objectForKey:kUDFirstLaunchVersionString]) {
        NSString *verString = [kUserDefaults objectForKey:kUDFirstLaunchVersionString];
        if ([verString isEqual:first]) {
            [self nonFirstLaunch];
        } else {
            [self firstLaunch];
        }
    } else {
        [self firstLaunch];
    }
    //向微信注册
    [WXApi registerApp:@"wx43b784f05f98e126"];
    [TMShareData shareData].window = self.window;
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                     selector:@selector(networkDidLogin:)
                         name:kJPFNetworkDidLoginNotification
                       object:nil];
    
    // 自定义消息推送
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    // 清除角标
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    
    return YES;
}

- (void)networkDidLogin:(NSNotification*)notification {
    
    NSLog(@"已登录");
    NSString *registrationIDStr = [JPUSHService registrationID];
    [TMShareData shareData].registrationID = registrationIDStr;
    NSLog(@"registrationIDStr=%@",registrationIDStr);
    
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSLog(@"收到的自定义消息 = %@",userInfo);
    // 消息内容
    NSString *content = [userInfo valueForKey:@"content"];
    // 包含type类型
    // type = 1 账号在别的设备登陆
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    if ([extras[@"type"] integerValue] == 1) {
        // 账号在别的设备登陆
        [self showAlertWithContent:content];
    }
    
}

- (void)registjPushWith:(NSDictionary *)launchOptions {
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    BOOL isProduction = NO;// NO为开发环境，YES为生产环境
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"bee119e74cd3f315cb25b13c"
                          channel:@"App Store"
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
}

- (void)firstLaunch {
    NSString *verString = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    [kUserDefaults setObject:verString forKey:kUDFirstLaunchVersionString];
    TMGuideViewController *vc = [[TMGuideViewController alloc] init];
    self.window.rootViewController = vc;
}

- (void)nonFirstLaunch {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    TMTabBarViewController *tabBar = [[TMTabBarViewController alloc] init];
    self.window.rootViewController = tabBar;
    [TMShareData shareData].tarBarVC = tabBar;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"deviceToken====%@",deviceToken);
    [JPUSHService registerDeviceToken:deviceToken];
    
}



-(NSString *)stringDevicetoken:(NSData *)deviceToken
{
    NSString *token = [deviceToken description];
    NSString *pushToken = [[[token stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    return pushToken;
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    
    completionHandler(UIBackgroundFetchResultNewData);
}
-(NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    return str;
}


// 账号在别的设备登陆弹窗
- (void)showAlertWithContent:(NSString *)content {
    // 弹出框背景
    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 80, 132)];
    customView.backgroundColor = [UIColor whiteColor];
    
    // 弹出框标题
    UILabel *titlelabel = [[UILabel alloc] init];
    titlelabel.textAlignment = NSTextAlignmentCenter;
    titlelabel.font = [UIFont boldSystemFontOfSize:14];
    titlelabel.text = @"下线通知";
    titlelabel.textColor = UIColorWithRGB(255,85,85);
    [customView addSubview:titlelabel];
    [titlelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(20);
    }];
    
    // 温馨提示
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.textAlignment = NSTextAlignmentLeft;
    tipLabel.font = [UIFont systemFontOfSize:13];
    tipLabel.text = content;
    tipLabel.textColor = [UIColor tm_LabelTextColor];
    [customView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(55);
    }];
    
    // 横线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor tm_separationBgColor];
    [customView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(90);
        make.height.mas_equalTo(1);
    }];
    // 取消
    UIButton *cancelButton = [[UIButton alloc] init];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [cancelButton setTitleColor:UIColorWithRGB(153, 153, 153) forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:cancelButton];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo((kScreenWidth - 80)/2);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo (91);
        make.left.mas_equalTo (0);
    }];
    
    // 确定
    UIButton *sureButton = [[UIButton alloc] init];
    [sureButton setTitle:@"重新登录" forState:UIControlStateNormal];
    sureButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [sureButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(sureButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:sureButton];
    [sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo((kScreenWidth - 80)/2);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo (91);
        make.right.mas_equalTo (0);
    }];
    
    // 竖线
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor tm_separationBgColor];
    [customView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo((kScreenWidth - 80)/2);
        make.top.mas_equalTo(101);
        make.width.mas_equalTo(1);
        make.bottom.mas_equalTo(-10);
    }];
    
    self.alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
    self.alert.layer.cornerRadius = 5;
    self.alert.layer.masksToBounds = YES;
    [self.alert show];
}

- (void)cancelButtonClick {
    [self.alert dismiss];
}
- (void)sureButtonClick {
    [self.alert dismiss];
    PBLoginViewController *vc = [[PBLoginViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    UINavigationController *nav = [[UIApplication sharedApplication] visibleNavigationController];
    [nav pushViewController:vc animated:YES];
}


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
//前台收到推送，可以采取必要的措施处理通知和更新APP的内容。
-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    //    UNNotificationRequest *request = notification.request; // 收到推送的请求
    //    UNNotificationContent *content = request.content; // 收到推送的消息内容
    //    NSNumber *badge = content.badge;  // 推送消息的角标
    //    NSString *body = content.body;    // 推送消息体
    //    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    //    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    //    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
    }
    // 指定系统如何提醒用户，有Badge、Sound、Alert三种类型可以设置
    // 如果不需提醒可传UNNotificationPresentationOptionNone
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
//当用户点击了通知的某个操作，需要进行相应处理，如跳转到某个界面
-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    //    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    //    UNNotificationContent *content = request.content; // 收到推送的消息内容
    //    NSNumber *badge = content.badge;  // 推送消息的角标
    //    NSString *body = content.body;    // 推送消息体
    //    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    //    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    //    NSString *title = content.title;  // 推送消息的标题
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
    }
    // 让系统知道你已处理完通知。
    completionHandler();
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}
#endif


//9.0前的方法，为了适配低版本 保留
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [self returnWithUrl:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [self returnWithUrl:url];
}

//9.0后的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    return [self returnWithUrl:url];
}

- (BOOL)returnWithUrl:(NSURL *)url {
    
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSString *resultStatus = resultDic[@"resultStatus"];
            NSLog(@"resultDic = %@",resultDic);
            NSString *result = resultDic[@"result"];
            NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSDictionary *response = dic[@"alipay_trade_app_pay_response"];
            NSLog(@"dic = %@",response);
            if ([resultStatus isEqualToString:@"9000"]) {
                [self paySuccess];
            }else if ([resultStatus isEqualToString:@"4000"] ){
                [self showHint:@"支付失败"];
            }else if ([resultStatus isEqualToString:@"8000"]){
                [self showHint:@"正在处理中"];
            }else if ([resultStatus isEqualToString:@"6001"]){
                [self showHint:@"用户中途取消"];
            }else if ([resultStatus isEqualToString:@"6002"]){
                [self showHint:@"网络连接出错"];
            }
        }];
    }else if ([url.host isEqualToString:@"pay"]) {
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }
    return YES;
}

// 支付成功
- (void)paySuccess {
    NSLog(@"支付成功");
    [TMShareData shareData].tarBarVC.selectedIndex = 0;
    PBPaySuccessViewController *vc = [[PBPaySuccessViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [[TMShareData shareData].homeNav pushViewController:vc animated:YES];
}
@end
